package com.d5xx.hunters.API;

import com.d5xx.hunters.scoreboard.GameScoreBoard;
import com.d5xx.hunters.scoreboard.LobbyScoreBoard;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.*;

import static com.d5xx.hunters.Variables.*;

@SuppressWarnings("unused")
public class HunterGame {
    private final Map<HunterPlayer, String> playerMap = new HashMap<>(); // (hunter, escapee)
    private List<HunterPlayer> players;
    private World world;
    private World world_nether;
    private World world_the_end;
    private List<World> worlds;
    private String type;

    public HunterGame(List<HunterPlayer> players) {
        this.players = players;
    }

    /**
     * 获取
     * @return playerMap
     */
    public List<HunterPlayer> getPlayers() {
        return players;
    }

    /**
     * 设置
     */
    public void addPlayer(HunterPlayer player) {
        players.add(player);
    }

    public void setPlayers(List<HunterPlayer> playerList) {
        players = new ArrayList<>(playerList);
    }

    public String getPlayerMode(HunterPlayer player) {
        return playerMap.get(player);
    }

    public boolean ready() {
        for (HunterPlayer player : players) {
            player.sendActionBar(player.getKeyMessage("player-waiting-finish-actionbar")); // 告诉玩家匹配成功
        }
        // 读取地图
        /*

        Bukkit.getScheduler().runTask(plugin, () -> {

        });

         */
        worlds = Hunter.getWorld();
        world = worlds.get(0);
        world_nether = worlds.get(1);
        world_the_end = worlds.get(2);

        if (world == null) return false;

        for (World world : worlds) {
            world.setDifficulty(Difficulty.HARD);
        }

        HunterPlayer escapee = players.get(new Random().nextInt(players.size())); // 在 [0, 列表大小) 之间随机出逃生者
        for (HunterPlayer player : players) { // 遍历玩家

            player.setType("game-fall");

            Bukkit.getScheduler().runTask(plugin, () -> player.getPlayer().setGameMode(GameMode.SURVIVAL));

            if (player.equals(escapee)) {
                playerMap.put(escapee, "escapee");
            }else {
                playerMap.put(player, "hunter");
            }

            String message = player.getKeyMessage("game-help");
            if (getPlayerMode(player).equals("hunter")) {
                message = message
                        .replace("%player-type%", player.getKeyMessage("game-start-type-hunter"))
                        .replace("%player-target%", player.getKeyMessage("game-start-target-hunter"));
            } else {
                message = message
                        .replace("%player-type%", player.getKeyMessage("game-start-type-escapee"))
                        .replace("%player-target%", player.getKeyMessage("game-start-target-escapee"));
            }
            player.getPlayer().sendMessage(message);
        }
        type =  "1v" + (playerMap.size() - 1);

        return true;
    }

    public void start() {
        for (HunterPlayer player : players) {
            Bukkit.getScheduler().runTask(plugin, () -> player.getPlayer().teleport(world.getSpawnLocation().add(0, 72, 0)));
            Bukkit.getScheduler().runTaskLater(plugin, () -> {
                // 计分板
                player.disableScoreboard();
                player.setScoreBoard(new GameScoreBoard(player));
                player.enableScoreboard();
            }, 20L);

        }

    }

    public void initMap() {
        final int[] i = {7};
        List<Location> circleBlocks = new ArrayList<>();
        Location center = world.getSpawnLocation().add(0, 70, 0); // 圆心坐标
        int radius = 7; // 圆的半径
        for (int x = -radius; x <= radius; x++) {
            for (int z = -radius; z <= radius; z++) {
                if (Math.sqrt(x * x + z * z) <= radius) {
                    // 计算当前坐标是否在圆的范围内
                    Location blockLocation = center.clone().add(x, 0, z);
                    circleBlocks.add(blockLocation); // 记录圆内方块的坐标
                    Block block = blockLocation.getBlock();
                    Bukkit.getScheduler().runTask(plugin, () -> block.setType(Material.CYAN_STAINED_GLASS)); // 使用白色玻璃方块
                }
            }
        }
        new BukkitRunnable() {
            @Override
            public void run() {
                if (!world.getPlayers().isEmpty()) {
                    i[0]--;
                    switch (i[0]) {
                        case 5:
                            replaceBlocks(circleBlocks, Material.BLUE_STAINED_GLASS);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.0f, 1.5f);
                            break;
                        case 4:
                            replaceBlocks(circleBlocks, Material.GREEN_STAINED_GLASS);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.0f, 1.5f);
                            break;
                        case 3:
                            replaceBlocks(circleBlocks, Material.YELLOW_STAINED_GLASS);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.0f, 1.5f);
                            break;
                        case 2:
                            replaceBlocks(circleBlocks, Material.RED_STAINED_GLASS);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.0f, 1.5f);
                            break;
                        case 1:
                            replaceBlocks(circleBlocks, Material.WHITE_STAINED_GLASS);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.0f, 1.5f);
                            break;
                        case 0:
                            replaceBlocks(circleBlocks, Material.AIR);
                            world.playSound(center, Sound.UI_BUTTON_CLICK, 1.5f, 2.0f);
                            break;
                        case -5:
                            for (HunterPlayer player : players) {
                                player.setType("game");
                                player.sendKeyMessage("game-pvp-enable" ,true);
                            }
                            this.cancel();

                    }
                }
            }
        }.runTaskTimer(plugin, 0L, 20L);
    }

    private void replaceBlocks(List<Location> circleBlocks, Material replacementMaterial) {
        for (Location location : circleBlocks) {
            Block block = location.getBlock();
            block.setType(replacementMaterial); // 替换为指定的方块
        }
    }

    public void endByHunter(HunterPlayer escapee) {
        Player bukkitescapee = escapee.getPlayer();
        // 给飞行状态
        bukkitescapee.setAllowFlight(true);
        bukkitescapee.setFlying(true);
        // 隐藏玩家
        Bukkit.getScheduler().runTask(plugin, () -> {
            for (HunterPlayer p : players) {
                p.getPlayer().hidePlayer(plugin, bukkitescapee);
            }
        });
        // 发送标题“你死了”
        String title = escapee.getKeyMessage("game-death-title");
        String subtitle = escapee.getKeyMessage("game-death-subtitle");
        final int[] i = {10};
        new BukkitRunnable() {
            @Override
            public void run() {
                i[0]--;
                bukkitescapee.sendTitle(
                        title,
                        subtitle.replace("%s%", String.valueOf(i[0])),
                        0,22,0);
                if (i[0] == 0) {
                    // 显示玩家
                    for (HunterPlayer p : players) {
                        p.getPlayer().showPlayer(plugin, bukkitescapee);
                    }
                    //送回大厅
                    sentToLobby(escapee);
                    this.cancel();
                }
            }
        }.runTaskTimer(plugin, 0L , 20L);

        // 猎人胜利
        players.remove(escapee);
        for (HunterPlayer winner : players) {
            winner.getPlayer().sendTitle(winner.getKeyMessage("game-win-title"), "", 5, 60, 5);
            new BukkitRunnable() {
                @Override
                public void run() {
                    winner.getPlayer().getInventory().clear();
                    sentToLobby(winner);
                    this.cancel();
                }
            }.runTaskLater(plugin, 200L);
        }
    }

    private void sentToLobby(HunterPlayer player) {
        Player bukkitplayer = player.getPlayer();
        player.setType("lobby");
        Bukkit.getScheduler().runTask(plugin, () -> {
            bukkitplayer.setGameMode(GameMode.ADVENTURE);
            bukkitplayer.teleport(Hunter.getLobby());
        });

        // 改变计分板
        player.disableScoreboard();
        player.setScoreBoard(new LobbyScoreBoard(player));
        player.enableScoreboard();
    }

    /**
     * 获取
     * @return world
     */
    public World getWorld() {
        return world;
    }

    public World getNether() {
        return world_nether;
    }

    public World getTheEnd() {
        return world_the_end;
    }

    public List<World> getWorlds() {
        return worlds;
    }

    /**
     * 设置
     */

    public String getType() { return this.type; }

}
